package org.toolbook.controller;

import java.util.Date;
import java.util.List;

import org.toolbook.interceptor.LoginInterceptor;
import org.toolbook.model.Foot;
import org.toolbook.model.User;
import org.toolbook.util.LogUtil;
import org.toolbook.util.PropUtil;
import org.toolbook.validator.AddFootValidator;
import org.toolbook.validator.UpdateFootValidator;

import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
/**
 * 足迹控制器
 * @author meigang
 * @date 2015-07-13 20:19
 *
 */
@Before(LoginInterceptor.class)
public class FootController extends Controller{
	String tablePre = PropUtil.getProperty("tablePre");
	/**
	 * 足迹首页
	 */
	public void index(){
		List<Foot> footList = Foot.dao.find("select * from "+tablePre+"foot order by time desc");
		setAttr("footList", footList);
		List<Foot> yearList = Foot.dao.find("select distinct YEAR(t.time) time from "+tablePre+"foot t order by t.time desc");
		setAttr("yearList", yearList);
		render("/WEB-INF/pages/fc/foot/list.jsp");
	}
	/**
	 * 跳转到添加足迹界面
	 */
	public void toAdd(){
		
		render("/WEB-INF/pages/fc/foot/add.jsp");
	}
	/**
	 * 添加足迹
	 */
	@Before(AddFootValidator.class)
	public void add(){
		User u = getSessionAttr(PropUtil.getProperty("SESSION_LOGIN_KEY"));
		Foot foot = new Foot().set("startPoint", getPara("startPoint"))
							.set("endPoint", getPara("endPoint"))
							.set("weather", getPara("weather"))
							.set("heart", getPara("heart"))
							.set("mind", getPara("mind"))
							.set("userId", u.get("id"));
		Date time = getParaToDate("time");
		if(time == null){
			foot.set("time", new Date());
		}else{
			foot.set("time",time);
		}
		
		foot.save();
		LogUtil.log.info("用户["+u.get("username")+"]添加足迹成功");
		index();
	}
	/**
	 * 删除
	 */
	public void delete(){
		Foot.dao.deleteById(getParaToInt(0));
		LogUtil.log.info("删除foot[id:"+getParaToInt(0)+"]");
		index();
	}
	/**
	 * 跳转到修改界面
	 */
	public void toUpdate(){
		Foot foot = Foot.dao.findById(getParaToInt(0));
		setAttr("foot", foot);
		render("/WEB-INF/pages/fc/foot/update.jsp");
	}
	/**
	 * 修改
	 */
	@Before(UpdateFootValidator.class)
	public void update(){
		User u = getSessionAttr(PropUtil.getProperty("SESSION_LOGIN_KEY"));
		Foot foot = Foot.dao.findById(getParaToInt("id"));
		foot.set("startPoint", getPara("startPoint"))
			.set("endPoint", getPara("endPoint"))
			.set("weather", getPara("weather"))
			.set("heart", getPara("heart"))
			.set("mind", getPara("mind"));
		Date time = getParaToDate("time");
		if(time == null){
			foot.set("time", new Date());
		}else{
			foot.set("time",time);
		}
		
		foot.update();
		LogUtil.log.info("用户["+u.get("username")+"]修改足迹成功");
		index();
	}
}
